package com.vtquang.magic.source;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;

import com.vtquang.magic.R;
import com.vtquang.magic.controls.IconMarker;
import com.vtquang.magic.controls.Marker;

public class GoogleDataSource extends NetworkDataSource {
	private static final String URL = "https://maps.googleapis.com/maps/api/place/search/json?location={0}&radius={1}&types={2}&sensor=false&key=AIzaSyC0nPWcSTEIsQmHiTCA3Wghz5Ft_bI_7jo";

	private static Bitmap icon = null;

	public GoogleDataSource(Resources res) {
		if (res==null) throw new NullPointerException();
		
		createIcon(res);
	}
	
	protected void createIcon(Resources res) {
		if (res==null) throw new NullPointerException();
		
		icon=BitmapFactory.decodeResource(res, R.drawable.twitter);
	}

	@Override
	public String createRequestURL(double lat, double lon, double alt, float radius, String locale) {
		return URL.replace("{0}", lat + "," + lon)
				  .replace("{1}", radius * 1000 + "")
				  .replace("{2}", "food");
	} 
	 
	@Override
	public List<Marker> parse(JSONObject root) {
		if (root==null) throw new NullPointerException();
		
		JSONObject jo = null;
		JSONArray dataArray = null;
    	List<Marker> markers=new ArrayList<Marker>();

		try {
			if(root.has("results")) dataArray = root.getJSONArray("results");
			if (dataArray == null) return markers;
			int top = Math.min(MAX, dataArray.length());
			for (int i = 0; i < top; i++) {					
				jo = dataArray.getJSONObject(i);
				Marker ma = processJSONObject(jo);
				if(ma!=null) markers.add(ma);
			}
		} catch (JSONException e) {
		    e.printStackTrace();
		}
		return markers;
	}
	
	private Marker processJSONObject(JSONObject jo) {
		if (jo==null) throw new NullPointerException(); 
		
		Marker ma = null;
		try {
			Double lat=null, lon=null;
			
			if(jo.has("geometry")) {
				JSONObject geo = jo.getJSONObject("geometry");
				if(geo.has("location")) {
					JSONObject loc = geo.getJSONObject("location");
					lat = loc.getDouble("lat"); 
					lon = loc.getDouble("lng"); 
				} 
			}  
			
			if(lat!=null) {  
				ma = new IconMarker(jo.getString("name"), 
						lat, 
						lon, 
						0,
						Color.GREEN,
						icon);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ma;
	}
}